<template>
  <div class="buy-button">
    <button type="button" class="btn" :disabled="!canbuy"
            @click="toggle">{{
      canbuy ?
      '立即购买' :
      '已经抢光' }}</button>
    <section class="buy-list-backdrop"
             @click.self="toggle"
             @touchmove.prevent
             v-show="isListActive">
      <div class="buy-list">
        <div class="header">
          V币支付更优惠哦(订单金额: {{ money }}元)
        </div>
        <div class="body">
          <ul>
            <li><a href="#" @click.prevent="buy('alipay')">支付宝支付</a></li>
            <li><a href="#" @click.prevent="buy('vmoney')">V币支付(余额: {{ vmoney
              }}元 <span v-if="vmoneyNoEnough" style="color: red;">[余额不足]</span>)
            </a></li>
            <li><a v-link="'/recharge'">V币打折充值</a></li>
          </ul>
        </div>
        <div class="footer" @click="toggle">取消</div>
      </div>
    </section>
  </div>
</template>
<script scoped>
  /*global alert location*/
  import _ from 'lodash'
  import Cookies from 'js-cookie'
  import userAgent from '../../assets/utils/userAgent.js'
  import webviewJavascriptBridge from '../../assets/utils/webviewJavascriptBridge.js'
  import Uid from '../../assets/utils/uid.js'
  import api from '../../assets/utils/api.js'
  import randomWord from '../../assets/utils/randomWord.js'

  export default {
    props: [
      'aid',
      'money',
      'canbuy',
      'title'
    ],
    data () {
      return {
        isListActive: false,
        vmoney: 0,
        scrollTop: 0
      }
    },
    computed: {
      vmoneyNoEnough () {
        return this.vmoney < this.money
      }
    },
    methods: {
      toggle () {
        this.isListActive = !this.isListActive
        if (this.isListActive) {
          Uid.getUid().then(res => {
            const uid = res.uid
            api.apiCall('indexVision', {
              uid: uid
            }).then(data => {
              if (data.returncode === '0') {
                this.vmoney = data['v-money']
              }
            })
          })
        }
      },
      buy (method) {
        if (method === 'vmoney' && this.vmoneyNoEnough) return
        const osType = userAgent.getOS()
        Uid.getUid().then(res => {
          const uid = res.uid

          api.apiCall('payOneday', {
            uid: uid,
            aid: this.aid
          }).then(data => {
            if (_.isFunction(window.vipbanlvPayCallback)) {
              window.vipbanlvPayCallback = undefined
            }
            window.vipbanlvPayCallback = (data) => {
              if (_.isString(data)) {
                data = _.attempt(JSON.parse.bind(null, data))
              }
              if (data.orderId === window.orderid) {
                try {
                  api.apiCall('payPayok', {
                    orderid: data.orderId,
                    payorderid: method === 'vmoney' ? data.orderId : data.payOrderId,
                    paytype: method === 'vmoney' ? 'vmoney' : 'alipay',
                    ordersign: data.ordersign
                  }).then(data => {
                    if (_.isString(data.returncode)) data.returncode = _.parseInt(data.returncode)
                    switch (data.returncode) {
                      case 0:
                        let randomKey = randomWord.getRandomWord(true, 8, 12)
                        Cookies.set(randomKey, {
                          username: data.username,
                          password: data.password
                        }, { expires: new Date(Date.now() + 1800000) })

                        this.$route.router.go({
                          name: 'AccountDetailPayok',
                          params: {
                            aid: this.aid,
                            randomKey: randomKey
                          },
                          replace: true
                        })
                        break
                      case -1:
                        console.error('payPayok接口返回错误：用户参数不正确')
                        break
                      case -2:
                        console.error('payPayok接口返回错误：订单状态不正确')
                        break
                      case -3:
                        console.error('payPayok接口返回错误：签名不正确')
                        break
                    }
                  }, err => {
                    window.alert(err.statusCode + ': ' + err.responseText)
                  })
                } catch (err) {
                  window.alert(err.message)
                }
              }
            }
            if (_.isString(data.returncode)) data.returncode = _.parseInt(data.returncode)
            switch (data.returncode) {
              case 0:
                // 将订单号赋给全局变量以便android调用接口时进行订单号验证
                window.orderid = data.orderid
                if (method === 'vmoney') {
                  try {
                    // window.alert(data.orderid)
                    api.apiCall('payPayok', {
                      orderid: data.orderid,
                      payorderid: data.orderid,
                      paytype: 'vmoney',
                      ordersign: ''
                    }).then(data => {
                      if (_.isString(data.returncode)) data.returncode = _.parseInt(data.returncode)
                      // window.alert(data.returncode)
                      switch (data.returncode) {
                        case 0:
                          let randomKey = randomWord.getRandomWord(true, 8, 12)
                          Cookies.set(randomKey, {
                            username: data.username,
                            password: data.password
                          }, { expires: new Date(Date.now() + 1800000) })

                          this.$route.router.go({
                            name: 'AccountDetailPayok',
                            params: {
                              aid: this.aid,
                              randomKey: randomKey
                            },
                            replace: true
                          })
                          break
                        case -1:
                          console.error('payPayok接口返回错误：用户参数不正确')
                          break
                        case -2:
                          console.error('payPayok接口返回错误：订单状态不正确')
                          break
                        case -3:
                          console.error('payPayok接口返回错误：签名不正确')
                          break
                      }
                    }, err => {
                      window.alert(err.statusCode + ': ' + err.responseText)
                    })
                  } catch (err) {
                    window.alert(err.message)
                  }
                } else if (osType === 'ios') {
                  webviewJavascriptBridge.init(bridge => {
                    // web -> ios
                    bridge.callHandler('vipbanlvPayCall', {
                      'orderId': data.orderid,
                      'price': this.money,
                      'title': this.title
                    }, response => {
                      console.log('JS got response', response)
                    })

                    // ios -> web
                    bridge.registerHandler('vipbanlvPayCallback', window.vipbanlvPayCallback)
                  })
                } else if (osType === 'android') {
                  if (_.isObject(window.vipbanlvFunc)) {
                    window.vipbanlvFunc.vipbanlvPayCall(`{"orderId": ${data.orderid}, "price": ${this.money}, "title": "${this.title}"}`)
                  }
                }
                break
              case -1:
                console.error('payOneday接口返回错误：用户参数不正确')
                break
              case -2:
                console.error('payOneday接口返回错误：账号不可购买')
                break
              case -3:
                console.error('payOneday接口返回错误：已购买过此账号')
                break
            }
          })
        }, () => {
          alert('下载xiaoshulinapp，更多免费账号天天享！')
          switch (osType) {
            case 'ios':
              location.href = 'https://itunes.apple.com/us/app/zhang-hao-ban-lu/id992488773?l=zh&ls=1&mt=8'
              break
            case 'android':
              location.href = 'https://www.pgyer.com/XPQt'
              break
            default:
              location.href = 'http://mp.weixin.qq.com/s?__biz=MzA3MjU0NDU3Ng==&mid=503801138&idx=1&sn=6f9c4a4c9e7d648304163fba94ff375a&scene=23&srcid=0715SrVJZhleC2rBVsBZNKw5#rd'
          }
        })
      }
    }
  }
</script>
